/**
 * Copyright 2023 Inc.
 **/
package com.myz.springclond2021.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * @author maoyz0621 on 2023/10/7
 * @version v1.0
 */
@EnableConfigurationProperties(DynamicThreadPoolProperties.class)
public class DynamicThreadPoolConfig {

    private final DynamicThreadPoolProperties dynamicThreadPoolProperties;

    public DynamicThreadPoolConfig(DynamicThreadPoolProperties dynamicThreadPoolProperties) {
        this.dynamicThreadPoolProperties = dynamicThreadPoolProperties;
    }

    private ThreadPoolTaskExecutor threadPoolExecutor;

    @Bean("dynamicThreadPoolExecutor")
    @ConditionalOnProperty(prefix = "thread", name = "enabled", matchIfMissing = false)
    public ThreadPoolTaskExecutor threadPoolExecutor() {
        threadPoolExecutor = new ThreadPoolTaskExecutor();
        threadPoolExecutor.setCorePoolSize(this.dynamicThreadPoolProperties.getCorePoolSize());
        threadPoolExecutor.setMaxPoolSize(this.dynamicThreadPoolProperties.getMaxPoolSize());
        return threadPoolExecutor;
    }

    @Bean("dynamicThreadPoolExecutor")
    @ConditionalOnMissingBean
    public ThreadPoolTaskExecutor dynamicThreadPoolExecutor() {
        threadPoolExecutor = new ThreadPoolTaskExecutor();
        threadPoolExecutor.setCorePoolSize(this.dynamicThreadPoolProperties.getCorePoolSize());
        threadPoolExecutor.setMaxPoolSize(this.dynamicThreadPoolProperties.getMaxPoolSize());
        return threadPoolExecutor;
    }

    public void resetThreadPool(DynamicThreadPoolProperties dynamicThreadPoolProperties) {
        threadPoolExecutor.setCorePoolSize(dynamicThreadPoolProperties.getCorePoolSize());
        threadPoolExecutor.setMaxPoolSize(dynamicThreadPoolProperties.getMaxPoolSize());
    }

    public ThreadPoolTaskExecutor getThreadPoolExecutor() {
        return threadPoolExecutor;
    }
}